<template>
	<div class="fix-all confirm-order" id="confirm_order">
		<div class="content">

			<dl class="order-cell cart-dl confirm-order-dl" :class="{'order-cell-model':app.model==2}">
				<!-- //todo dt会自动检测？ -->
				<div class="md-padding dt layout-row">
					<span class="td1 layout-flex ell" v-if="app.model==2">{{order.extended.numberPlate?(order.extended.numberPlate+order.extended.numberPlateUnit):"支付金额"}}</span><span class="td1 layout-flex ell" v-if="app.model==1">{{appUrlInfo.tableName+" 号台桌"}}</span><span class="td2">x{{order.cart.qty}}</span><span class="td3">￥{{order.subtotal || 0}}</span>
				</div>
				<section class="sec-content" id="sec_content">
					<div id="sec_content_wrap">
						<dd class="md-padding text-default layout-row" v-for='item in order.cart.items'>
							<div class="item-l layout-flex layout-column layout-center">
								<p class="item-p-title ">
									<span class="text-accent item-title vm">{{item.inventoryName}}</span>
									<span v-if="item.modifiers"><span v-for="modifier in item.modifiers.items"><span v-for="option in modifier.options" v-if="modifier.options.length!=0" class="item-info">{{option.name}}</span></span></span>
								</p>
								<p class="text-muted text-color-info item-p-info ell">{{item.extended.description}}</p>
							</div>
							<div class="item-r layout-row layout-center"><span class="inventory-count qty">x{{item.qty}}</span></div>
							<div class="item-rr layout-row layout-center"><span class="text-accent amount">￥{{item.amount}}</span></div>
						</dd>
					</div>
				</section>
			</dl>


			<div class="bottom text-default" id='confirm_order_bottom'>
				<div class="md-padding" :class="{ 'dn': app.model!=1}">
					<label class="text-accent l">就餐人数：<span class="text-color-accent">&nbsp;*</span></label>
					<!-- onkeypress="if(!(/[/d.]/.test(String.fromCharCode(event.keyCode)))){this.value = "123";console.log(123);}"  -->
					<!--  v-model="order.headCount" -->
					<div class="cell"><input id="confirem_input_1"  value={{order.headCount}} type="number" min="1" max="2" @keyup="validHeadCount($event)"  @blur.stop="fixBottom1($event)" @focus.stop="fixBottom($event)" placeholder='请输入就餐人数'  ></input></div>
				</div>
				<div class="md-padding">
					<label class="text-accent l">备注：</label>
					<div  class="cell"><input id="confirem_input_2" type="text" maxlength="50" @focus.stop.prevent="fixBottom($event)" @blur.stop.prevent="fixBottom1($event)" placeholder='口味、偏好等其他要求' v-model="order.description"></input></div>
				</div>
				<button  v-bind:class="{ 'disabled': (app.model!=2)&&!(order.headCount > 0)}" class="btn-buttom" v-gesture:tap.stop.prevent="confirmOrder">{{"app.model!=2"?"确认下单":"确认下单 通知厨房"}}</button>
			</div>
		</div>
		<!-- 提示对话框 -->
		<weui-dialog v-show="isShowDialog" type="alert" :title="errMsg" @weui-dialog-confirm="handleDialogAction('确认', 2)"></weui-dialog>
		<!-- 等待下单界面  -->
		<waiting-order v-if="isShowWaitingOrder"></waiting-order>
	</div>
</template>


<style lang='sass'>
	@import '../assets/sass/global/themes.scss';
	.confirm-order{background: white}

	.confirm-order .order-cell{bottom: 150px;width: 100%}
	.confirm-order .order-cell-model{bottom: 100px;width: 100%}

	/*可以公用的css*/
 /*hack	打包后很奇怪*/

	.order-cell{position: absolute;top: 0;    background: #f0f0f0;}
	.order-cell dt,.order-cell .dt{padding: 0 15px;box-sizing:border-box;line-height: 60px;background: white;z-index: 5;position: relative;width: 100%;}
	.order-cell .sec-content{margin-top: 5px;position: absolute;bottom: 0;top: 60px;width: 100%;overflow-y:scroll;background: #f0f0f0;z-index: 3;}
	.confirm-order .bottom.shadow:before{content: "";width: 100%;height: 700px;position: absolute;top: -700px;pointer-events:none;z-index: 3;}
	.order-cell dt .td1,.order-cell .dt .td1{font-size: 16px;}
	.order-cell dt .td2,	.order-cell .dt .td2{min-width: 90px;font-size: 14px;text-align: right;float: right;}
	.order-cell dt .td3,.order-cell .dt .td3{min-width: 90px;font-size: 20px;color: $font-color-primary;text-align: right;float: right;}
	.order-cell dd,.order-cell .dd{background: white;}
	.order-cell dd .item-r{min-width: 55px;justify-content:flex-end;}
	.order-cell dd .item-rr{min-width: 90px;justify-content:flex-end;}

	.confirm-order .bottom{position: absolute;bottom: 0;width: 100%;}
	.confirm-order .bottom .btn-buttom{width: 100%;line-height: 50px;border: none;color:white;background:$font-color-primary;font-size: $font-size-accent;}
	.confirm-order .bottom .btn-buttom:active{background: $btn-color-active !important;}
	.confirm-order .bottom .btn-buttom.disabled{background: #DADADA;pointer-events:none;}
	.confirm-order .bottom > div{line-height: 50px;border-top: 1px solid #e3e3e3;height: 50px;padding: 0 15px;}
	.confirm-order .bottom > div:first-child{border: none;}
	.confirm-order .bottom > div label{padding-right: 10px;border: none;}
	.confirm-order .bottom > div input{border: none;width:100%;}
	.confirm-order .bottom > div input::-webkit-outer-spin-button,.confirm-order .bottom > div input::-webkit-inner-spin-button{-webkit-appearance: none !important;}
	.confirm-order .bottom > div input:focus {border: none;-webkit-appearance:none}

	/*weui dialog css*/
	.confirm-order,.select-pay{
		 .weui_dialog_alert{.weui_dialog{border-radius: 5px;}
		  .weui_btn_dialog{margin: 10px 20px 42px 20px;background-color: $bg-color-primary;color: white;}
			.weui_dialog_ft:after{display: none;}
			.weui_mask{z-index: 10;}
		 }
		}

</style>

<script type="text/javascript">
 import {ordering} from "../vuex/actions";
 import api from '../api';
 import BusFn from "../business/bus-fn";
 import Order from "../business/order";
 import {store, storeWithExpiration} from '../lib/store';
	import {OrderList} from '../config';

	export default{
		vuex:{
			getters:{
				vuexData: (state) =>state.app.x,
				app: (state) => state.app
			},
			actions:{
				ordering
			}
		},
		route: {
			canActivate : function(transition){
				// if(transition.from.name=="inventory-list"&&!transition.to.query.show){
				// 	return transition.abort("confirm-order canActivate abort");
				// }
				transition.next()
			}
		},

		data: function(){
			return {
				isShowWaitingOrder:false,
				//props
				isShowConfirmOrder: this.$parent.isShowConfirmOrder,
				isShowCompleteOrder: this.$parent.isShowCompleteOrder,
				order: this.$parent.order,
				allOrder: this.$parent.allOrder,
				appUrlInfo: this.$parent.appUrlInfo,
				errMsg:"该台座尚未开台，请联系服务员开台",
				isShowDialog:false
			}
		},
		ready: function(){
			let o  = document.getElementById('confirm_order_bottom');
			if(o.offsetHeight < document.getElementById('sec_content_wrap').offsetHeight) {
				o.classList.add('shadow');
			}

			document.getElementById("confirem_input_1").value = this.order.headCount;

			// $('#phone').bind('focus',function(){
			//             $('.bottom_fix').css('position','static');
			//             //或者$('#viewport').height($(window).height()+'px');
			//         }).bind('blur',function(){
			//             $('.bottom_fix').css({'position':'fixed','bottom':'0'});
			//             //或者$('#viewport').height('auto');
			//         });
		},
		beforeDestroy: function(){
			document.getElementById("confirm_order").style.position = "fixed";
			document.getElementById('app').classList.remove('input-upspring');
		},
		// props:{
		// 	isShowConfirmOrder:{
		// 		require: true
		// 	},
		// 	isShowCompleteOrder:{
		// 		require: true
		// 	},
		// 	order:{
    //     type:Object,
    //     required:true
    //   }
		// },
		components: {
			'waiting-order': require('./waiting-order'),
			'weui-dialog': require('../components/dialog/dialog'),
		},
		methods:{
			handleDialogAction: function(){
				this.isShowDialog = false;
			},
			confirmOrder: function(){
				document.getElementById("confirem_input_2").blur();
				document.getElementById("confirem_input_1").blur();
				const self = this;
				if(self.isShowWaitingOrder) return;
				document.getElementById('app').classList.remove('input-upspring');

				self.isShowWaitingOrder = true;
				console.log(self.order);
				switch (self.app.model) {
					case 2:
					{
						Order.setNewOrderId(self.order);
						self.order.emptyProcessStatus();
						self.order.orderNo = self.order.id;
						self.order.terminalName ="WO";
						api.ordering(self.order).then(response => {
					    console.log(response);
					    let result = response.data;
					    switch (+result.code) {
					      case 200:
								{

									//下单成功
									self.$broadcast('dataReturn', true);
									self.ordering(self.order);
									BusFn.completeOrder(self.order, result.data);
									self.isShowWaitingOrder = false;
									self.isShowConfirmOrder = false;
									self.isShowCompleteOrder = true;
									self.$router.go({ name: 'select-pay'});

									break;
								}
					      default:
								self.errorConfirm();
					    }

					  }, response => {
					    console.log(response);
							self.errorConfirm();
					  });


						break;
					}

					default:
						{
							let _url = '/api/stores/' + self.order.storeId + '/confirm-order/longitude/' + "123" + '/latitude/' + "123";
							self.$http.post(_url,JSON.stringify(self.order)).then(
								response => {
									if (response.data.success) {
										self.$broadcast('dataReturn', true);
										setTimeout(function(){
											self.isShowWaitingOrder = false;
											self.isShowConfirmOrder = false;
											self.isShowCompleteOrder = true;
											self.$router.go({ name: 'complete-order'});
										}, 2000);
										self.order.mergeOrder(self.allOrder);
										// debugger
									} else {
										if(response.data.message.indexOf("该台桌尚未开台") > 0){
											self.$broadcast('dataReturn', false);
											self.isShowWaitingOrder = false;
											self.isShowDialog = true;
										} else {
											self.errorConfirm();
										}
										// console.log(response.data.message);
									}
								},
								response => {
									self.errorConfirm();
									console.log('/api/stores/' + self.order.storeId + '/confirm-order/longitude/' + position.coords.longitude + '/latitude/' + position.coords.latitude + ' error');
								}
							);
						}
				}

			},
			validHeadCount: function(e){
				const self = this;
				setTimeout(function(){
					e.target.value=e.target.value.replace(/\D+/g,'');
					if (e.target.value>50 || e.target.value==0){
						e.target.value = "";
						// self.order.headCount = "";
					}
					self.order.headCount = e.target.value;
				},0);
			},
			fixBottom: function(e){
				// console.log('00', this.appUrlInfo.window.height, window.innerHeight);
				const _w = window;
				const self = this;
				e.target.isInput = true;
				setTimeout(function(){
					// console.log('01', self.appUrlInfo.window.height,  _w.innerHeight);
					if(self.appUrlInfo.window.height - _w.innerHeight < 200){
						document.getElementById("confirm_order").style.position = "absolute";
						document.getElementById('app').classList.add('input-upspring');
					}
				},500);
			},
			fixBottom1: function(e){
				e.target.isInput = false;
				setTimeout(function(){
					if (e.target.id == "confirem_input_1"){
						if (document.getElementById("confirem_input_2").isInput) {return}
					}
					if (e.target.id == "confirem_input_2"){
						if (document.getElementById("confirem_input_1").isInput) {return}
					}
					document.getElementById("confirm_order").style.position = "fixed";
					document.getElementById('app').classList.remove('input-upspring');
				}, 50);
			},
			errorConfirm: function(){
				const self = this;
				self.$broadcast('dataReturn', false);
				setTimeout(function(){
					self.isShowWaitingOrder = false;
				}, 2000);
			}
		}
	}
</script>

<!-- // .container 设置了 overflow 属性, 导致 Android 手机下输入框获取焦点时, 输入法挡住输入框的 bug
	 // 相关 issue: https://github.com/weui/weui/issues/15
	 // 解决方法:
	 // 0. .container 去掉 overflow 属性, 但此 demo 下会引发别的问题
	 // 1. 参考 http://stackoverflow.com/questions/23757345/android-does-not-correctly-scroll-on-input-focus-if-not-body-element
	 //    Android 手机下, input 或 textarea 元素聚焦时, 主动滚一把
	 if (/Android/gi.test(navigator.userAgent)) {
			 window.addEventListener('resize', function () {
					 if (document.activeElement.tagName == 'INPUT' || document.activeElement.tagName == 'TEXTAREA') {
							 window.setTimeout(function () {
									 document.activeElement.scrollIntoViewIfNeeded();
							 }, 0);
					 }
			 })
	 } -->
